package com.attendance.sz;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.attendance.sz.exception.DBException;
import com.attendance.sz.local.LocalCardRecordDao;
import com.attendance.sz.net.AbsAPICallback;
import com.attendance.sz.net.SmartAPI;
import com.attendance.sz.utils.ClsPublic;
import com.attendance.sz.utils.DeviceActionBase;
import com.attendance.sz.utils.Entity;
import com.attendance.sz.utils.MyApplication;
import com.attendance.sz.utils.Session;
import com.attendance.sz.utils.TagEntity;
import com.attendance.sz.utils.Version;
import com.attendance.sz.utils.logMa;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yc.utilslib.utils.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import Decoder.BASE64Decoder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;

public class DetailInfoActivity extends BaseNewActivity {
    private static final String LOGTAG = "martrin";

    public static DetailInfoActivity activityTwo;
    List<TagEntity> list;
    Bundle bundle;
    ImageView imgPhoto;
    Bitmap bitmap = null;
    TextView tvNameValue, tvStudentValue, tvCardTypeValue;
    TextView txtTitle, tvName, num, tvStudentNO, tvNum;
    static LocalCardRecordDao localCardRecordDao = null;
    SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
    String sFileNamePng;
    Context myContext;
    LinearLayout LinearLayoutDetailInfo;//整个
    String card, creditCard, Number, Name;
    ExecutorService mThread;
    Map<String, String> map = new HashMap<String, String>();
    static String mPhotoPath = Environment.getExternalStorageDirectory().getPath() + "/EmpPhoto";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("TAG","------------------------DetailInfo onCreate() Start------------------------");
        //获得SharedPreferences对象
        Timer timerFinsh = new Timer();
        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            setContentView(R.layout.activity_detailinfoori);
            //setContentView(R.layout.activity_detailinfo);
        } else {
            setContentView(R.layout.activity_detailinfo);
            //背景变亮
            Handler handler = ((MyApplication) getApplication())
                    .getHandler();

            Message message = new Message();
            message.what = 7;
            message.obj = myContext;
            if (handler != null) {
                handler.sendMessage(message);
            }

        }

        map = MyApplication.getInstance().getMap();
        tvNameValue = (TextView) findViewById(R.id.tvNameValue);

        LinearLayoutDetailInfo = (LinearLayout) findViewById(R.id.LinearLayoutDetailInfo);
        if("0".equals(Session.getVisibility())){
            LinearLayoutDetailInfo.setBackgroundResource(R.drawable.back_empty);
        }else{
            LinearLayoutDetailInfo.setBackgroundResource(R.drawable.back);
        }

        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            LinearLayoutDetailInfo.setBackgroundResource(R.drawable.backori);
        }
        activityTwo = this;
        myContext = this;

        if (localCardRecordDao == null) localCardRecordDao = new LocalCardRecordDao();

        txtTitle = (TextView) findViewById(R.id.txttitle);
        txtTitle.setText(Session.getCompanyInfo());
        tvName = (TextView) findViewById(R.id.tvName);
        num = (TextView) findViewById(R.id.num);
        tvNum = (TextView) findViewById(R.id.tvNum);
        tvStudentNO = (TextView) findViewById(R.id.tvStudentNO);
        txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 48);
        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            txtTitle.setVisibility(View.VISIBLE);
        }

        if (MyApplication.getApp().getSimulater()) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, 600);
            params.setMargins(0, 40, 0, 0);
            findViewById(R.id.llcontent).setLayoutParams(params);
            txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 38);
        } else {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, 400);
            params.setMargins(0, 40, 0, 0);
            findViewById(R.id.llcontent).setLayoutParams(params);
        }

        imgPhoto = (ImageView) findViewById(R.id.imgPhoto);

        LayoutParams para;
        para = imgPhoto.getLayoutParams();
        para.height = 350;
        para.width = 400;
        imgPhoto.setLayoutParams(para);

        tvStudentValue = (TextView) findViewById(R.id.tvStudentValue);
        tvCardTypeValue = (TextView) findViewById(R.id.tvCardTypeValue);

        View home = findViewById(R.id.LinearLayoutDetailInfo);
        home.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
//                MyApplication.getInstance().setCode(null);
            }
        });

        Intent intent = getIntent();
        card = intent.getStringExtra("card");
        creditCard = intent.getStringExtra("creditCard");
        Number =MyApplication.getInstance().getNumber();
        Name = MyApplication.getInstance().getName();
        try {
            Log.d("TAG","DetailInfo:"+ MyApplication.getInstance().getCardSerial());

            String filePath = mPhotoPath + "/" + MyApplication.getInstance().getCard() + ".jpg";
            File f = new File(filePath);
            if(f.exists())
            {
                Glide.with(DetailInfoActivity.this).load(filePath).into(imgPhoto);
            }
            else {
                post(SmartAPI.BASE_URL+"/GetEmployeeImage?CardID="+MyApplication.getInstance().getCardSerial(), filePath);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (card != null) {
            sFileNamePng = card; //扫描
        } else {
            sFileNamePng = creditCard; //刷卡
        }
        Bundle bundleIntent = this.getIntent().getExtras();
        if (bundleIntent != null)
            list = bundleIntent
                    .getParcelableArrayList("serializable_list");
        bundle = new Bundle();

        if (DetailInfoActivity.activityTwo != null) {
            Timer timer = new Timer();
            TimerTask tast = new TimerTask() {
                @Override
                public void run() {
                    finish();
                }
            };
            timer.schedule(tast, 2000);
        }

        SetBundle();
        mThread = MyApplication.singleThreadExecutor;
        SetValue(bundle);
        Log.d("TAG","------------------------DetailInfo onCreate() End------------------------");
    }

    public void SetValue(Bundle bundle) {
        if (bundle != null) {
            Log.d("TAG","------------------------DetailInfo SetValue() Start------------------------");
            tvStudentValue.setText(DeviceActionBase.GetStudentNo(bundle
                    .getString("vale_studentno")));
            String cardType = DeviceActionBase.GetCardNoOrLineNo(bundle
                    .getString("vale_cartype"));
            tvCardTypeValue.setText(cardType + "类卡");
            //String path = Session.getDownAdvUrl() + "/" + sFileNamePng + ".jpg";
            tvNameValue.setText(Name);
            num.setText(Number);
            tvName.setText("姓名:");
            tvNum.setText("工号:");
            tvStudentNO.setText("签到成功");
            // 取机号
            String strMachineNo = Version.GetMachineNo();// 取十进制的字符串,如:12
            String sUploadFlag = "0";// 是否上传此条记录的标志(0--没有上传,1--已上传)
            String sDemo = "0"; //上传失败次数
            String strDateTime = formatter.format(new Date(System
                    .currentTimeMillis()));
            byte[] bb = ClsPublic.DexString2Bytes(strDateTime);//"150801200948";//将之转为0F0801140930
            strDateTime = ClsPublic.MyBytes2HexString(bb);
            saveDataToDb(bundle, strMachineNo, sUploadFlag, sDemo, strDateTime);
            //播放音
            Handler handler = ((MyApplication) getApplication())
                    .getHandler();
            Message message = new Message();
            message.what = 6;
            message.obj = myContext;

            if (handler != null)
                handler.sendMessage(message);

            Log.d("TAG","------------------------DetailInfo SetValue() End------------------------");
        }

    }

    private void saveDataToDb(final Bundle bundle, final String strMachineNo, final String sUploadFlag, final String sDemo, final String strDateTime) {
        Log.d("SaveDataToDb","vale_no="+bundle.getString("vale_no"));
        mThread.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (card == null) {
                        // 1.插入数据库
                        localCardRecordDao.AddCardRecord(new String[]{
                                bundle.getString("vale_no"),
                                bundle.getString("vale_lineno"),
                                bundle.getString("vale_name"),
                                bundle.getString("vale_cartype"), "", strDateTime,
                                strMachineNo, sUploadFlag, sDemo});
                    }
                } catch (DBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 读卡
     */
    public void SetBundle() {
        // Tag 0x01 物理卡号 Len 0x04 Value[0:3] 低字节在前
        TagEntity te = DeviceActionBase.GetValueByTay(list, "01");// 01042669CCDD
        // 物理卡号:2669CCDD
        if (te != null) {
            bundle.putString("vale_no", creditCard);
        } else {
            if (card == null) {
                if (MyApplication.getInstance() != null && MyApplication.getInstance().getCardSQ() != null)
                bundle.putString("vale_no", MyApplication.getInstance().getCardSQ().replace(" ",""));
            }

        }
        // Tag 0x10 卡流水号 Len 0x04 Value[0:3] 低字节在前
        te = DeviceActionBase.GetValueByTay(list, "10");// 100401000000
        // 卡流水号:01000000
        if (te != null) {
            bundle.putString("vale_lineno", te.getValue());
            // bundle.putString("vale_lineno",
            // DeviceActionBase.GetCardNoOrLineNo(te.getValue()));
        } else {
            bundle.putString("vale_lineno", "0");
        }

        // Tag 0x11 用户卡类 Len 0x01 Value 1~32
        te = DeviceActionBase.GetValueByTay(list, "11");// 110101 用户卡类:01
        if (te != null) {
            bundle.putString("vale_cartype", te.getValue());
            // bundle.putString("vale_cartype",
            // DeviceActionBase.GetCardNoOrLineNo(te.getValue()));
        } else {
            bundle.putString("vale_cartype", "");
        }

        // Tag 0x12 用户姓名 Len 0xnn 参数长度可变 Value[0:0xnn-1] GB2312码
        te = DeviceActionBase.GetValueByTay(list, "12");// 1206CDF5D0A1C0F6
        // 用户姓名:王小丽(CDF5D0A1C0F6)
        if (te != null) {
            // bundle.putString("vale_name",
            // DeviceActionBase.GetChineseFromGB2312(te.getValue()));
            bundle.putString("vale_name",
                    DeviceActionBase.GetChineseFromGB2312(te.getValue()));
        } else {
            bundle.putString("vale_name", "");
        }

        // Tag 0x13 身份证号 Len 0x09 Value[0:8] BCD码，最后1位为”x”时，用0xA表示
        te = DeviceActionBase.GetValueByTay(list, "13");
        if (te != null) {
            bundle.putString("vale_cardno", te.getValue());
            // bundle.putString("vale_cardno",
            // DeviceActionBase.GetCardNo(te.getValue()));
        } else {
            bundle.putString("vale_cardno", "");
        }

        // Tag 0x14 学工号 Len 0xnn 参数长度可变 Value[0:0xnn-1]
        // BCD码（位数为奇数时，最后1字节的低4bits为0xF）
        te = DeviceActionBase.GetValueByTay(list, "14");
        if (te != null) {
            bundle.putString("vale_studentno", te.getValue());
            // bundle.putString("vale_studentno",
            // DeviceActionBase.GetStudentNo(te.getValue()));
        } else {
            bundle.putString("vale_studentno", "");
        }

    }

    private BroadcastReceiver changeContentReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("action", action);

            if ("com.changecontentreceiver.receiver".equals(action)) {
                synchronized (this) {

                    SetValue(intent.getExtras());

                }
            }
        }
    };

    @Override
    public void onDestroy() {
         Log.d("LOGTAG", "onDestroy()...");
//        MyApplication.getInstance().setCardSerial(0);
        Glide.get(this).clearMemory();//清理内存缓存  可以在UI主线程中进行
        logMa.d(LOGTAG, ":" + "startCunt=0");
        ClsPublic.setstartCunt(0);
        activityTwo = null;
        localCardRecordDao = null;
        MyApplication.getInstance().setCardSQ(StringUtils.EMPTY);
        super.onDestroy();
        if (bitmap != null) {
            if (!bitmap.isRecycled())
                bitmap.recycle();
            bitmap = null;
        }

    }
    private void post(final String url, final String path) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Log.d("TAG","GetEmpPhoto:" + url);
        final Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                if(e!=null){
                    Log.d("TAG", "message=" +e.getMessage());
                }
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if(response.code() == 200){
                    Gson gson = new Gson();
                    String res = response.body().string();
                    Entity entity = gson.fromJson(res, Entity.class);
                    if(entity.getReturnMsg().contains("失败")|| TextUtils.isEmpty(entity.getReturnMsg())){
                        Log.d("TAG","GetEmpPhoto："+ entity.getReturnMsg());
                            DetailInfoActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.get(DetailInfoActivity.this).clearMemory();
                                }
                            });
                    }else{
                        boolean isRes = GenerateImage(entity.getReturnMsg(), path);
                        if(isRes){
                            Log.d("TAG","GetEmpPhoto:返回成功");
                            DetailInfoActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Glide.with(DetailInfoActivity.this).load(path).into(imgPhoto);
                                    }
                             });
                        }


                    }


                }
                Log.d("TAG", "message=" + response.message() + "code=" + response.code());

            }
        });

    }
    private  void   GetImg(final String CardID, final String  path  ){
        Subscriber subscriber = new AbsAPICallback<Entity>(DetailInfoActivity.this) {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onNext(Entity entity) {
              //  Log.d("TAG","返回："+ entity.getReturnMsg());
                GenerateImage(entity.getReturnMsg(),Environment.getExternalStorageDirectory().getPath()+"/"+path+".jpg");
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
               // Log.d("TAG","错误："+e.getMessage());
            }
        };
      //  SmartAPI.getInstance().GetEmployeeImage(subscriber,CardID);

    }
    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            isExist(mPhotoPath);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     *
     * @param path 文件夹路径
     */
    public static void isExist(String path) {
        File file = new File(path);
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            file.mkdir();
        }
    }
}